package com.easy.robot.framework

import ai.easy.robot.utils.logd
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.Message
import android.os.Messenger

/**
 * 负责节点与主服务的连接
 */
class MasterConnector constructor(val ctx: Context, initor: MasterConnector.() -> Unit? = {}) {

    init {
        initor()
    }

    var onConnected: (() -> Unit)? = null
    fun onConnect(f: () -> Unit) {
        onConnected = f
    }

    var isConnected: Boolean = false
    //get() = field
        private set(value) {
            field = value
        }

    internal var messenger: Messenger? = null
        get() = field

    private val conn =
            object : ServiceConnection {
                override fun onServiceDisconnected(name: ComponentName?) {
                    logd("service disconnected")
                    isConnected = false
                    messenger = null
                }

                override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                    logd("service connected")
                    messenger = Messenger(service)
                    isConnected = true
                    onConnected?.invoke()
                }
            }

    private var isBounded = false
    /**
     * 连接MasterService服务
     */
    fun connect(servClass: Class<*>) {
        if (!isConnected && !isBounded) {
            val i = Intent()
            i.setClass(ctx, servClass)
            ctx.bindService(i, conn, Context.BIND_AUTO_CREATE)
            isBounded = true
        }
    }

    /**
     * 连接进程外的MasterService服务
     */
    fun connect(masterPackageName: String, masterServiceName: String) {
        if (!isConnected && !isBounded) {
            val i = Intent()
            i.setComponent(ComponentName(masterPackageName, masterServiceName))
            ctx.bindService(i, conn, Context.BIND_AUTO_CREATE)
            isBounded = true
        }
    }

    /**
     * 断开服务
     */
    fun disconnect() {
        if (isBounded) {
            ctx.unbindService(conn)
            isBounded = false
        }
        isConnected = false
    }

    /**
     * 发布消息
     */
    fun publish(topic: String, msg: Bundle) {
        logd("pub:${topic} ->${msg}")
        val m = Message.obtain()
        m.what = MasterService.NODE_MSG_PUB
        m.obj = topic
        m.data = msg
        messenger?.send(m)
    }


}